package com.android.webrtcsdkdev

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.os.PowerManager
import android.provider.Settings
import android.util.Log
import android.view.View
import android.widget.AdapterView
import android.widget.Button
import android.widget.EditText
import android.widget.Spinner
import android.widget.TextView
import android.widget.Toast
import androidx.core.app.ActivityCompat


class SettingStreamActivity : Activity() {
    val TAG = "MainActivity"
    private var edt_uri: EditText? = null
    private var edt_device_id: EditText? = null
    private var bt_start: Button? = null
    private var info: TextView? = null
    private var encoder: Spinner? = null
    private var sizeSpinner: Spinner? = null
    private var cardSizeSpinner: Spinner? = null
    private var densitySpinner: Spinner? = null
    private var fpsSpinner: Spinner? = null
    private var bitrate: EditText? = null
    private var authEdit: EditText? = null
    private var videoCodec = "VP8"
    private var direct = 0
    private var width = 0
    private var height = 0;
    private var videofps = 30
    private val REQUEST_EXTERNAL_STORAGE = 1
    private var density = 480
    private var cardWidth = 1080
    private var cardHeight = 1920;
    private var gpsDelay = 300

    private val permissions = arrayOf(
        Manifest.permission.CAMERA,
        Manifest.permission.RECORD_AUDIO,
        Manifest.permission.INTERNET,
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.WRITE_EXTERNAL_STORAGE,
        Manifest.permission.WRITE_EXTERNAL_STORAGE
    )

    fun verifyStoragePermissions(activity: Activity?) {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {//Build.VERSION_CODES.R
            if (!Environment.isExternalStorageManager()) {
                val intent = Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
                startActivity(intent);
                return;
            }
        }else{
                //检测是否有写的权限
                val permission = ActivityCompat.checkSelfPermission(
                    activity!!,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
                )
                if (permission != PackageManager.PERMISSION_GRANTED) {
                    // 没有写的权限，去申请写的权限，会弹出对话框
                    ActivityCompat.requestPermissions(
                        this,
                        permissions,
                        REQUEST_EXTERNAL_STORAGE
                    )

                }
        }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.d(TAG, "onDestroy")
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_setting_stream)
        verifyStoragePermissions(this)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            val intent = Intent()
            val packageName = packageName
            val pm = getSystemService(POWER_SERVICE) as PowerManager
            if (!pm.isIgnoringBatteryOptimizations(packageName)) {
                intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS)
                intent.setData(Uri.parse("package:$packageName"))
                startActivity(intent)
                Toast.makeText(
                    this,
                    "ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS",
                    Toast.LENGTH_LONG
                ).show()
            }
        }
        SharedPHelper.getInstance(this).open("vclusters", 1)


        val displayMetrics = resources.displayMetrics
        var screenWidth = displayMetrics!!.widthPixels
        var screenHeight = displayMetrics.heightPixels
        Log.d(TAG, "screenWidth:$screenWidth screenHeight:$screenHeight")
        edt_uri = findViewById(R.id.edt_uri)
        edt_device_id = findViewById(R.id.edt_device_id)
        bt_start = findViewById(R.id.bt_start)
        info = findViewById(R.id.info);
        encoder = findViewById(R.id.encoder_spinner)
        sizeSpinner = findViewById(R.id.spinner_size)
        fpsSpinner = findViewById(R.id.encoder_fps)
        bitrate = findViewById(R.id.bitrate)
        authEdit = findViewById(R.id.auths)
        cardSizeSpinner = findViewById(R.id.card_size)
        densitySpinner = findViewById(R.id.card_density)

        encoder!!.setSelection(1)
        fpsSpinner!!.setSelection(2)
        sizeSpinner!!.setSelection(3)
        cardSizeSpinner!!.setSelection(0)
        densitySpinner!!.setSelection(0)

        val serverUrl = SharedPHelper.getInstance(this).getString(VideoConstant.STREAM_SERVER_URL)
        val deviceId = SharedPHelper.getInstance(this).getString(VideoConstant.STREAM_DEVICE_ID)

        if (serverUrl.isNotEmpty()) {
            edt_uri?.setText(serverUrl)
        }

        if (deviceId.isNotEmpty()) {
            edt_device_id?.setText(deviceId)
        }


        setUpSessionButton()
    }

    private fun setUpSessionButton() {
        bt_start!!.setOnClickListener {

            val serverUrl = edt_uri?.text.toString()
            val deviceId = edt_device_id?.text.toString()

            val intent = Intent()
            intent.setClass(this@SettingStreamActivity, StreamActivity::class.java)
            intent.putExtra("uri", serverUrl)
            intent.putExtra("room", deviceId)
            intent.putExtra("videocodec", videoCodec)
            intent.putExtra("bitrate", bitrate!!.text.toString())
            intent.putExtra("videofps", videofps.toString())
            intent.putExtra("auths", authEdit!!.text.toString())

            var localVideoCallEnabled = true
            var localAudioCallEnabled = true
            var localVideoReceiveEnabled = true
            var localAudioReceiveEnabled = true
            var remoteVideoCallEnabled = true
            var remoteAudioCallEnabled = true
            var remoteVideoReceiveEnabled = true
            var remoteAudioReceiveEnabled = true


            if (serverUrl.isNotEmpty()) {
                SharedPHelper.getInstance(this)
                    .putString(VideoConstant.STREAM_SERVER_URL, serverUrl)
            }

            if (deviceId.isNotEmpty()) {
                SharedPHelper.getInstance(this).putString(VideoConstant.STREAM_DEVICE_ID, deviceId)
            }


            intent.putExtra("localVideoCallEnabled", localVideoCallEnabled)
            intent.putExtra("localAudioCallEnabled", localAudioCallEnabled)
            intent.putExtra("localVideoReceiveEnabled", localVideoReceiveEnabled)
            intent.putExtra("localAudioReceiveEnabled", localAudioReceiveEnabled)
            intent.putExtra("remoteVideoCallEnabled", remoteVideoCallEnabled)
            intent.putExtra("remoteAudioCallEnabled", remoteAudioCallEnabled)
            intent.putExtra("remoteVideoReceiveEnabled", remoteVideoReceiveEnabled)
            intent.putExtra("remoteAudioReceiveEnabled", remoteAudioReceiveEnabled)
            intent.putExtra("width", width)
            intent.putExtra("height", height)
            intent.putExtra("cardWidth", cardWidth)
            intent.putExtra("cardHeight", cardHeight)
            intent.putExtra("density", density)
            intent.putExtra("gpsDelay", gpsDelay)
            intent.putExtra("sessionId", "")

            startActivity(intent)
        }
        encoder?.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(
                parent: AdapterView<*>?,
                view: View?,
                position: Int,
                id: Long
            ) {
                if (position == 0) {
                    videoCodec = "H264 Baseline"
                } else if (position == 1) {
                    videoCodec = "H264 High"
                } else if (position == 2) {
                    videoCodec = "H265"
                }
            }

            override fun onNothingSelected(parent: AdapterView<*>?) {

            }
        }
        fpsSpinner?.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(
                parent: AdapterView<*>?,
                view: View?,
                position: Int,
                id: Long
            ) {
                if (position == 0) {
                    videofps = 15;
                } else if (position == 1) {
                    videofps = 20;
                } else if (position == 2) {
                    videofps = 30;
                } else if (position == 3) {
                    videofps = 35;
                } else if (position == 4) {
                    videofps = 40;
                } else if (position == 5) {
                    videofps = 45;
                } else if (position == 6) {
                    videofps = 50;
                } else if (position == 7) {
                    videofps = 55;
                } else if (position == 8) {
                    videofps = 60;
                }
            }

            override fun onNothingSelected(parent: AdapterView<*>?) {

            }
        }


        sizeSpinner?.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(
                parent: AdapterView<*>?,
                view: View?,
                position: Int,
                id: Long
            ) {
                if (position == 0) {
                    width = 640;
                    height = 360;
                } else if (position == 1) {
                    width = 800;
                    height = 450;
                } else if (position == 2) {
                    width = 960;
                    height = 540;
                } else if (position == 3) {
                    width = 1280;
                    height = 720;
                } else if (position == 4) {
                    width = 1920;
                    height = 1080;
                } else if (position == 5) {
                    width = 2280;
                    height = 1020;
                } else if (position == 6) {
                    width = 2560;
                    height = 1440;
                } else if (position == 7) {
                    width = 2560;
                    height = 1600;
                }
            }

            override fun onNothingSelected(parent: AdapterView<*>?) {

            }
        }

        cardSizeSpinner?.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(
                parent: AdapterView<*>?,
                view: View?,
                position: Int,
                id: Long
            ) {
                if (position == 0) {
                    cardWidth = 720;
                    cardHeight = 1280;
                } else if (position == 1) {
                    cardWidth = 1080;
                    cardHeight = 1920;
                } else if (position == 2) {
                    cardWidth = 1080;
                    cardHeight = 2400;
                } else if (position == 3) {
                    cardWidth = 1440;
                    cardHeight = 2560;
                } else if (position == 4) {
                    cardWidth = 1600;
                    cardHeight = 2560;
                } else if (position == 5) {
                    cardWidth = 1280;
                    cardHeight = 720;
                } else if (position == 6) {
                    cardWidth = 1920;
                    cardHeight = 1080;
                } else if (position == 7) {
                    cardWidth = 2400;
                    cardHeight = 1080;
                } else if (position == 8) {
                    cardWidth = 2560;
                    cardHeight = 1440;
                } else if (position == 9) {
                    cardWidth = 2560;
                    cardHeight = 1600;
                }
            }

            override fun onNothingSelected(parent: AdapterView<*>?) {

            }
        }
        densitySpinner?.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(
                parent: AdapterView<*>?,
                view: View?,
                position: Int,
                id: Long
            ) {
                if (position == 0) {
                    density = 320;
                } else if (position == 1) {
                    density = 480;
                } else if (position == 2) {
                    density = 560;
                }
            }

            override fun onNothingSelected(parent: AdapterView<*>?) {

            }
        }
    }
}
